package com.xbongbong.saas.model.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.pojo.dto.InsertDTO;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.dao.competitor.CompetitorUserDao;
import com.xbongbong.saas.domain.entity.competitor.CompetitorUserEntity;
import com.xbongbong.saas.model.CompetitorUserModel;
import org.apache.commons.collections4.CollectionUtils;
import org.elasticsearch.action.support.WriteRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author gaojie
 * @version v1.0
 * @date 2022/8/10 18:40
 * @since v1.0
 */
@Service("competitorUserModel")
public class CompetitorUserModelImpl implements CompetitorUserModel {

    @Resource
    CompetitorUserDao competitorUserDao;

    @Resource
    TransferSubFormHelper transferSubFormHelper;

    @Resource
    PaasEsModel paasEsModel;

    @Override
    public Integer insert(CompetitorUserEntity entity) throws XbbException {
        Integer result = competitorUserDao.insert(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserAndDepTeamToFormData(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM, entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM);
        paasEsModel.insert(insertDTO);
        return result;
    }

    @Override
    public Integer update(CompetitorUserEntity entity) throws XbbException {
        Integer result = competitorUserDao.update(entity);
        PaasFormDataEntity paasFormDataEntity = transferSubFormHelper.transferUserAndDepTeamToFormData(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM, entity);
        InsertDTO insertDTO = paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM);
        paasEsModel.update(insertDTO);
        return result;
    }

    @Override
    public List findEntitys(Map<String, Object> param) {
        List<CompetitorUserEntity> entities = competitorUserDao.findEntities(param);
        return entities;
    }

    @Override
    public Integer getEntitysCount(Map<String, Object> param) {
        Integer count = competitorUserDao.getEntitysCount(param);
        return count;
    }

    @Override
    public List findEntitysWithoutSub(Map<String, Object> param) {
        return null;
    }


    @Override
    public CompetitorUserEntity getByKey(Long id, String corpid) {
        CompetitorUserEntity competitorUser = competitorUserDao.getByKey(id, corpid);
        return competitorUser;
    }

    @Override
    public List<CompetitorUserEntity> findBaseEntities(Map<String, Object> params) {
        return competitorUserDao.findBaseEntitys(params);
    }

    @Override
    public void refreshProductUser(SaasFormSaveDTO saasFormSaveDTO, Long dataId, String corpid, List<Object> visbleDept, List<Object> visbleUser) throws XbbException {
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.CORPID, corpid);
        param.put(StringConstant.DEL, 0);
        param.put(StringConstant.DATA_ID, dataId);
        Long now = DateTimeUtil.getInt();
        List<CompetitorUserEntity> competitorUserList = findEntitys(param);
        List<CompetitorUserEntity> visbleUserList = new ArrayList<>();
        List<CompetitorUserEntity> visbleDeptList = new ArrayList<>();
        for(CompetitorUserEntity competitorUserEntity : competitorUserList){
            if(Objects.equals(competitorUserEntity.getType(), BasicConstant.ZERO)){
                visbleUserList.add(competitorUserEntity);
            }else if(Objects.equals(competitorUserEntity.getType(),BasicConstant.ONE)){
                visbleDeptList.add(competitorUserEntity);
            }
        }
        insertRelationId(saasFormSaveDTO,visbleUser,visbleUserList,dataId,corpid,now,BasicConstant.ZERO);
        insertRelationId(saasFormSaveDTO,visbleDept,visbleDeptList,dataId,corpid,now,BasicConstant.ONE);
    }

    @Override
    public void inserBatch(List<CompetitorUserEntity> insetBatchList) throws XbbException {
        competitorUserDao.insertBatch(insetBatchList);
        List<PaasFormDataEntity> paasFormDataEntities = transferSubFormHelper.transferUserAndDepTeamToFormDataList(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM, insetBatchList);

        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (PaasFormDataEntity paasFormDataEntity : paasFormDataEntities) {
            insertDTOList.add(paasEsModel.getSaveDTO(paasFormDataEntity, IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM));
        }
        paasEsModel.insertBatch(insertDTOList);
    }

    @Override
    public void deleteBatch(String corpid, List<Long> delIdList) throws XbbException {
        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid",corpid);
        param.put("idIn",delIdList);
        List<CompetitorUserEntity> competitorUserEntityList = findEntitys(param);
        competitorUserDao.deleteBatch(corpid,delIdList);
        List<InsertDTO> updateBatch = new ArrayList<>();
        for (CompetitorUserEntity entity : competitorUserEntityList){
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put(StringConstant.DEL, DelEnum.DELETE.getDel());
            map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM);
            updateBatch.add(insertDTO);
        }
        paasEsModel.updateBatch(updateBatch);
    }

    @Override
    public void deleteBatch(String corpid, List<Long> dataIdList, List<CompetitorUserEntity> competitorUserEntityList) throws XbbException {
        //数据库删除
        competitorUserDao.deleteBatch(corpid,dataIdList);
        //封装es删除信息
        List<InsertDTO> esRemoveList = competitorUserEntityList.stream().map(user -> {
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM.getType() + "_" + corpid + "_" + user.getId());
            insertDTO.setParent(corpid + "_" + user.getDataId());
            Map<String, Object> source = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            source.put(StringConstant.DEL, DelEnum.DELETE.getDel());
            source.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            insertDTO.setSource(source);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM);
            return insertDTO;
        }).collect(Collectors.toList());
        //es删除可见人信息
        paasEsModel.updateBatch(esRemoveList);
    }

    @Override
    public void delete(CompetitorUserEntity competitorUserEntity) throws XbbException {
        competitorUserEntity.setDel(1);
        competitorUserEntity.setUpdateTime((long) DateUtil.getInt());
        competitorUserDao.update(competitorUserEntity);
        paasEsModel.delete(competitorUserEntity.getId(), competitorUserEntity.getCorpid(), IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM, competitorUserEntity.getDataId());
    }

    @Override
    public void deleteBatch(String corpid, List<CompetitorUserEntity> competitorUserEntityList, WriteRequest.RefreshPolicy refreshPolicy, Integer del) throws XbbException {
        if (CollectionUtils.isEmpty(competitorUserEntityList)) {
            return;
        }
        List<Long> removeIdList = new ArrayList<>();
        List<InsertDTO> insertDTOList = new ArrayList<>();
        for (CompetitorUserEntity entity : competitorUserEntityList){
            removeIdList.add(entity.getId());
            InsertDTO insertDTO = new InsertDTO();
            insertDTO.setEsId(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM.getType() + "_" + corpid + "_" + entity.getId());
            insertDTO.setParent(corpid + "_" + entity.getDataId());
            Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("del", del);
            map.put(StringConstant.UPDATE_TIME, DateTimeUtil.getInt());
            insertDTO.setSource(map);
            insertDTO.setIndexTypeEnum(IndexTypeEnum.IDX_SAAS_COMPETITOR_TEAM);
        }
        competitorUserDao.deleteBatch(corpid,removeIdList);
        paasEsModel.updateBatch(insertDTOList, refreshPolicy);
    }

    /**
     *
     * date: 2022/8/18 5:17 下午
     * @author yingjf
     * @param saasFormSaveDTO:
     * @param visbleUser: 此次提交的
     * @param competitorUserList: 现有的
     * @param dataId:
     * @param corpid:
     * @param now:
     * @param type:
     */
    private void insertRelationId(SaasFormSaveDTO saasFormSaveDTO, List<Object> visbleUser,
                                  List<CompetitorUserEntity> competitorUserList,Long dataId,String corpid,
                                  Long now,Integer type) throws XbbException{
        List<Object> relationIdList = new ArrayList<>();
        List<Object> copyOldRelationIdList = new ArrayList<>();
        Map<String,List<CompetitorUserEntity>> relationMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<CompetitorUserEntity> competitorUserEntityList;
        for(CompetitorUserEntity competitorUser : competitorUserList){
            relationIdList.add(competitorUser.getRelationId());
            copyOldRelationIdList.add(competitorUser.getRelationId());
            competitorUserEntityList = Objects.isNull(relationMap.get(competitorUser.getRelationId())) ? new ArrayList<>() : relationMap.get(competitorUser.getRelationId());
            competitorUserEntityList.add(competitorUser);
            relationMap.put(competitorUser.getRelationId(), competitorUserEntityList);
        }
        List<Object> visbleStringUser = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(visbleUser)) {
            for (Object obj : visbleUser) {
                visbleStringUser.add(obj.toString());
            }
            visbleUser = visbleStringUser;
        }else{
            visbleUser = visbleStringUser;
        }
        List<CompetitorUserEntity> insertList = new ArrayList<>();
        List<Long> deleteList = new ArrayList<>();
        CompetitorUserEntity competitorUserEntity;
        if(null != visbleUser){
            //visbleUser 是选择的可见的人 或可见的部门,productUserList 是从数据库里查询出来的可见人或部门实体集合,这里是考虑关联表在保存后存入可见人或可见部门
            if(saasFormSaveDTO.getIsNew()) {
                for (Object object : visbleUser) {
                    competitorUserEntity = new CompetitorUserEntity();
                    competitorUserEntity.setCorpid(corpid);
                    competitorUserEntity.setDataId(dataId);
                    competitorUserEntity.setRelationId(object.toString());
                    competitorUserEntity.setType(type);
                    insertList.add(competitorUserEntity);
                }
            }else {
                copyOldRelationIdList.retainAll(visbleUser);
                relationIdList.removeAll(copyOldRelationIdList);
                visbleUser.removeAll(copyOldRelationIdList);
                // 删掉的
                if(CollectionsUtil.isNotEmpty(relationIdList)){
                    for(Object object : relationIdList){
                        competitorUserEntityList = relationMap.get(String.valueOf(object));
                        competitorUserEntityList.forEach(userEntity -> deleteList.add(userEntity.getId()));
                    }
                    deleteBatch(corpid,deleteList);
                }
                // 新加的
                if(CollectionsUtil.isNotEmpty(visbleUser)){
                    for(Object object : visbleUser){
                        competitorUserEntity = new CompetitorUserEntity();
                        competitorUserEntity.setCorpid(corpid);
                        competitorUserEntity.setDataId(dataId);
                        competitorUserEntity.setRelationId(object.toString());
                        competitorUserEntity.setType(type);
                        insertList.add(competitorUserEntity);
                    }
                }
            }

            if (CollectionsUtil.isNotEmpty(insertList)) {
                inserBatch(insertList);
            }
        }
    }



}
